package com.zxy.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.zxy.model.FileInfo;
import com.zxy.model.UploadInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/api/upload")
public class UpLoadController {

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.domain}")
    private String domain;

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
//        第一步：获取文件的名称
        String name = uploadInfo.getName();
//        名称唯一标识
//        name = IdUtil.fastSimpleUUID() + "_" + name;
//        想要有序
        name =System.currentTimeMillis() + "_" + name;
        String base64 = uploadInfo.getBase64();
//        第二步：使用hutool工具
        String[] strArray = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(strArray[1]);
//        第三步：字节数组存到某个位置 hutool工具中
//        String path = "D:\\File\\nginx-1.25.1\\html\\images\\"+name;
        String path = uploadPath+name;
        FileUtil.writeBytes(bytes,path);
//        return "http://img.206.com/images/"+name;
        return domain + "/images/" + name;
    }

    private static List<String> imgExts = CollUtil.newArrayList("jpg","png","gif","jpeg");
    @GetMapping
    public List<FileInfo> getFiles(){
        List<String> names = FileUtil.listFileNames("D:/File/nginx-1.25.1/html/images/");
        List<String> names2 = names.stream().filter(item -> {
            String[] ext = StrUtil.splitToArray(item, '.');
            return imgExts.contains(ext[ext.length - 1]);
        }).collect(Collectors.toList());

//        把上面的 List<String> names 一个一个遍历，遍历完之后转成 new FileInfo 这个对象
//        这个对象会放在下面List<FileInfo> fileInfos 里面，就可以返回它
//        List<FileInfo> fileInfos = names.stream().map(name -> {
//            return new FileInfo(name, "http://img.206.com/images/" + name);
//        }).collect(Collectors.toList());

//        lambad 表达式
        List<FileInfo> fileInfos = names2.stream()
                .map(name -> new FileInfo(name, domain+ "/images/" + name))
                .collect(Collectors.toList());
        return fileInfos;


    }
}
